<template>
    <div id="add_allocation_goods_tpl">
        <el-dialog
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        top="10vh"
        :before-close="handleClose">
            <div slot="title">
                <span>添加商品</span>
                <span style="font-size: 14px; color: #ff7068">{{ '（单号：' + titles.transferOrderId + '、调出-调入门店：' + titles.senderStore + '-' + titles.receiverStore + '、创建时间：' + titles.gmtApply + '）'}}</span>
            </div>
            <el-row :gutter="20" style='margin-bottom: 10px'>
                <el-col :span="5">
                    <div class="grid-content">
                        <el-select style="100%" size="mini" clearable v-model="brandId" filterable remote reserve-keyword placeholder="选择品牌" :remote-method="remoteMethod" :loading="loading">
                            <el-option
                            v-for="item in brandList"
                            :key="item.brandId"
                            :label="item.brandName"
                            :value="item.brandId">
                            </el-option>
                        </el-select>
                    </div>
                </el-col>
                <el-col :span="5">
                    <div class="grid-content">
                        <el-cascader style="100%" size="mini" v-model="categoryIds" :options="categoryList" :props='pro' clearable placeholder="请选择类目"></el-cascader>
                    </div>
                </el-col>
                <el-col :span="5">
                    <div class="grid-content">
                        <el-input size="mini" v-model="specName" type="text" placeholder="输入颜色或尺码模糊查询"></el-input>
                    </div>
                </el-col>
                <el-col :span="5">
                    <div class="grid-content">
                        <el-input size="mini" v-model="skuSpuCode" type="text" placeholder="输入sku或spu模糊查询"></el-input>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="grid-content col_float_right">
                        <el-button size="mini" type="primary" @click="getStockGoodsList">搜 索</el-button>
                        <el-button size="small" @click="handleClickClear">清 空</el-button>
                    </div>
                </el-col>
                
            </el-row>
            
            <el-table stripe :data="tableData" ref="multipleTable" border  @select="handleSelectGoods" @selection-change="handleSelectChange"	 @select-all= "handleSelectAll" @cell-click="handleClickCell"  max-height="300px">
                <el-table-column type="selection"  width="55" :selectable="handleSelectable"></el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="品牌" prop="brandName" show-overflow-tooltip></el-table-column>
                <el-table-column label="品类" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.categoryName1+ '/' + scope.row.categoryName2 + '/' + scope.row.categoryName3}}
                    </template>
                </el-table-column>
                <el-table-column label="SKU" prop="skuCode" show-overflow-tooltip width="150"></el-table-column>
                <el-table-column label="SPU" prop="spuCode" show-overflow-tooltip></el-table-column>
                <el-table-column label="款号" prop="goodsCode" show-overflow-tooltip></el-table-column>
                <el-table-column label="规格" prop="specName" width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="可用库存" prop="stockQty" width="80"></el-table-column>
                <el-table-column label="调拨数量" width="80" prop="allocationNum">
                    <template slot-scope="scope">
                        <el-input class="num-input" :ref="'inputRef' + scope.row.skuCode" size="mini"  v-model="scope.row.allocationNum" clearable  @input="handleCellInputChange(scope.row)"></el-input>
                    </template>
                </el-table-column>
            </el-table>
            <page :total="total" :page="page" :size="size" @handlepagechange="handlePageChange" @handleSizeChange="handleSizeChange"></page>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="handleSaveAllocationGoods">继续添加</el-button>
                <el-button size="small" type="primary" @click="handleSubmit">完成返回</el-button>
            </span>
        </el-dialog>
    </div> 
</template>
<script>
    import page from '../../../commonComponents/page'
    export default {
        props: ['isShowAddGoods', 'titles', 'transferId', 'checkedGoods'],
        components: {page},
        data() {
            return {
                autofocus: true,
                tableData: [],
                page: 1,
                size: 50,
                total: 0,
                brandId: '',
                skuSpuCode: '',
                specName: '',
                brandList: [],
                categoryList: [],
                categoryIds: [],
                loading: false,
                isCheckedGoods: [],
                allocationGoods: [],
                pro: {
                    value: 'categoryId',
                    label: 'categoryName',
                    checkStrictly: true 
                },
                isSure: true
            }
        },
        computed: {
            dialogVisible: {
                get() {
                    return this.isShowAddGoods
                },
                set() {}
            }
        },
        mounted() {
            this.getCategoryList()
            this.getBrandList()
            this.getStockGoodsList()
            this.getAllocationGoodsList()
        },
        methods: {
            /**获取调拨单已有商品 */
            getAllocationGoodsList() {
                try{
                    this.$server.stockControlApi.getAllocationGoodsList(this.transferId).then(res => {
                        console.log(res, 'res')
                        this.isCheckedGoods= res.data
                    })
                }catch(err) {this.$paramsError(err)}
            },
            /**获取商品类目 */
            getCategoryList() {
                this.$server.goodsControlApi.getCategoryList().then(res => {
                    this.categoryList= res.data
                }).catch()
            },

            remoteMethod(query) {
                if (query !== '') {
                    this.loading = true;
                    this.getBrandList(query)
                    
                } else {
                    this.brandList = [];
                }
            },
            getBrandList(keywords) {
                try {
                    let query= {
                        keyword: keywords || ''
                    }
                    this.$server.goodsControlApi.getBrandListByKeywords(query).then(res => {
                        this.brandList= res.data
                        this.loading= false
                    }).catch(err => {
                        console.log(err)
                    })
                }catch(error) {
                    this.$paramsError(error.message)
                }
            },
            getStockGoodsList() {
                try{
                    let params= {
                        brandId: this.brandId,
                        categoryId1: this.categoryIds.length > 0 ? this.categoryIds[0] : '' ,
                        categoryId2: this.categoryIds.length > 1 ? this.categoryIds[1] : '' ,
                        categoryId3: this.categoryIds.length > 2 ? this.categoryIds[2] : '' ,
                        goodsCode: '',
                        skuSpuCode: this.skuSpuCode,
                        specName: this.specName
                    }
                    let query= {
                        page: this.page,
                        size: this.size,
                        transferId: this.transferId
                    }
                    this.$server.stockControlApi.getStockGoodsList(query, params).then(res => {
                        res.data.forEach(item => {
                            item.allocationNum= ''
                            item.type= 'input'
                        })
                        this.tableData= res.data
                        this.total= res.total
                    })
                }catch(err) {
                    this.$paramsError(err)
                }
            },
            handlePageChange(page) {
                this.page= page
                this.getStockGoodsList()
            },
            handleSizeChange(size) {
                this.size= size
                this.getStockGoodsList()
            },
            handleClose() {
                this.$confirm('确认关闭？').then(_ => {
                    this.$emit('cancelAddAllocationGoods', false)
                    this.$emit('getAllocationsDetails')
                }).catch(_ => {});
            },
            handleSubmit() {
                /**提交任务，并关闭页面 */
                try{
                    if(this.allocationGoods.length < 1) {
                        this.$confirm('请选择要添加的商品!')
                        this.isSure= false
                    }else{
                        this.allocationGoods.forEach(item => {
                            if(item.applyQty <1) {
                                this.isSure= false
                            }else{
                                this.isSure= true
                            }
                        })
                    }
                    if(this.isSure) {
                        this.$server.stockControlApi.addAllocationGoods(this.allocationGoods).then(res => {
                            this.$emit('cancelAddAllocationGoods', false)
                            this.$emit('getAllocationsDetails', '') 
                        })
                    }else{
                        this.$confirm('请检查所选商品数量')
                        this.isSure= true
                    }
                }catch(err) {this.$paramsError(err)}
                //this.handleSaveAllocationGoods()
            },
            handleSaveAllocationGoods() {
                /**添加任务商品 不关闭页面 */
                try{
                    if(this.allocationGoods.length > 0) {
                        this.allocationGoods.forEach(item => {
                            if(item.applyQty <1) {
                                this.isSure= false
                            }else{
                                this.isSure= true
                            }
                        })
                    }else {
                        this.$confirm('请选择添加商品')
                        this.isSure= false
                    }
                    if(this.isSure) {
                        this.$server.stockControlApi.addAllocationGoods(this.allocationGoods).then(res => {
                            this.$message({
                                message: res.message,
                                type: 'success',
                                duration: 1000,
                              
                            })
                            this.allocationGoods= []
                            this.$refs.multipleTable.clearSelection();
                            this.getAllocationGoodsList()
                        })
                    }else{
                        this.$confirm('请检查所选商品数量')
                        this.isSure= true
                    }
                }catch(err) {this.$paramsError(err)}
            },
            /**全选 */
            handleSelectAll(val) {
                let params= []
                val.forEach(item => {
                    params.push(
                        {
                            applyQty: +item.allocationNum,
                            brandCode: item.brandCode,
                            brandName: item.brandName,
                            goodsName: item.goodsName,
                            goodsPrice: item.tagPrice,
                            goodsQty: null,
                            skuCode: item.skuCode,
                            specName: item.specName,
                            spuCode: item.spuCode,
                            stockQty: item.stockQty,
                            transferId: this.transferId
                        }
                    )
                })
                this.allocationGoods= params
            },
            handleSelectable(row, index) {
                // console.log(row)
                if(this.isCheckedGoods.indexOf(row.skuCode)  > -1 || row.stockQty < 1) {
                    return false;
                }else{
                    return true;
                }
            },
            handleSelectChange(val) {
                //console.log(val, 'cahnge')
            },
            /**手动勾选商品 */
            handleSelectGoods(val, row) {
                let params= []
                console.log(val, 'val')
                val.forEach(item => {
                    params.push(
                        {
                            applyQty: +item.allocationNum,
                            brandCode: item.brandCode,
                            brandName: item.brandName,
                            goodsName: item.goodsName,
                            goodsPrice: item.tagPrice,
                            goodsQty: null,
                            skuCode: item.skuCode,
                            specName: item.specName,
                            spuCode: item.spuCode,
                            stockQty: item.stockQty,
                            transferId: this.transferId
                        }
                    )
                })
                console.log(params, 'params')
                this.allocationGoods= params
            },
            handleClickCell(row, column, cell, event) {
                if(column.property == 'allocationNum') {
                    row.type="input"
                    this.$nextTick(() => {
                        console.log(this.$refs)
                        let id = 'inputRef'+row.skuCode;
                        this.$refs[id].focus();
                    })
                }
            },

            handleCellInputChange(scope) {
                console.log(scope.allocationNum, '1233')
                if(/^[1-9]\d*|0$/.test(+scope.allocationNum)) {
                    if(scope.allocationNum > scope.stockQty) {
                        this.$confirm('申请数量超出库存数量').then(_ => {
                            scope.allocationNum= ''
                        }).catch(err => {
                            scope.allocationNum= ''
                        })
                    }else{
                       // scope.type= 'label'
                       if(this.allocationGoods.length > 0) {
                           this.allocationGoods.forEach(item => {
                               if(item.skuCode == scope.skuCode) {
                                   item.applyQty= +scope.allocationNum
                               }
                           })
                       }
                    }
                }else{
                    this.$confirm('申请数量为非负整数').then(_ => {
                        scope.allocationNum= ''
                    }).catch(err => {
                        scope.allocationNum= ''
                    })
                }
            },
            /**清空筛选 */
            handleClickClear() {
                this.brandId= ''
                this.categoryIds= []
                this.skuSpuCode= ''
                this.specName= ''
                this.getStockGoodsList()
            }
        }
    }
</script>